﻿#include "dxstdafx.h"
#include "DialogManager.h"
#include "Support/GUI/GuiConfigIO.h"
#include "Strategy/GUI/MainInterface/GuiTopBarFolder.h"
#include "Strategy/GUI/ProvinceInterface/GuiProvince.h"
#include "GuiEditors.h"

DialogManager::~DialogManager()
{
	for (auto &it : mapDialogManager)
	{
		SAFE_DELETE(it.second);
	}
}

void DialogManager::Init()
{
#define DialogManagerInsert( STR, CLASS ) mapDialogManager.insert( std::make_pair( STR, new CLASS() ))

	mapDialogManager.clear();
	DialogManagerInsert(L"GuiEditors00", GuiEditors);

	DialogManagerInsert(L"StrategyProvince00", GuiProvince);
	//Strategy Main
	DialogManagerInsert(L"StrategyMainTopBarFolder00", GuiTopBarFolder);

}

CDXUTDialog* DialogManager::GetDialog(std::wstring str)
{
	auto iter = mapDialogManager.find(str);
	if (iter == mapDialogManager.end())
	{
		return NULL;
	}
	else
	{
		return mapDialogManager[str];
	}
}

void DialogManager::InitResource(CDXUTDialogResourceManager* pManager)
{
	for (const auto &it : mapDialogManager)
	{
		CDXUTDialog* pDialog = it.second;
		if (pDialog)
		{
			pDialog->Init(pManager);
		}
	}
}

HRESULT DialogManager::OnD3D9CreateDevice(IDirect3DDevice9* pd3dDevice)
{
	HRESULT hr = S_OK;
	for (const auto &it : mapDialogManager)
	{
		CDXUTDialog* pDialog = it.second;
		if (NULL == pDialog)
		{
			return -1;
		}
		pDialog->SetCallback(StaticOnEvent, (void*)pDialog);
	}
	return hr;
}

HRESULT DialogManager::ResetDevice()
{
	HRESULT hr = S_OK;
	for (const auto &it : mapDialogManager)
	{
		CDXUTDialog* pDialog = it.second;
		if (NULL == pDialog)
		{
			return -1;
		}
		pDialog->SetLocation(pDialog->m_pProperty->nOffsetX, pDialog->m_pProperty->nOffsetY);
		pDialog->SetSize(pDialog->m_pProperty->nWidth, pDialog->m_pProperty->nHeight);
	}
	return hr;
}

HRESULT DialogManager::OnRender(float fElapsedTime)
{
	HRESULT hr = S_OK;
	for (const auto &it : mapDialogManager)
	{
		CDXUTDialog* pDialog = it.second;
		if (NULL == pDialog)
		{
			return -1;
		}
		V_RETURN(pDialog->OnRender(fElapsedTime));
	}
	return hr;
}

bool DialogManager::MsgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	for (const auto &it : mapDialogManager)
	{
		CDXUTDialog* pDialog = it.second;
		CHECK_RE_FALSE(pDialog);

		if (pDialog->MsgProc(hWnd, uMsg, wParam, lParam) || pDialog->CDXUTDialog::MsgProc(hWnd, uMsg, wParam, lParam))
		{
			return true;
		}

	}
	return false;
}

//--------------------------------------------------------------------------------------
void WINAPI DialogManager::StaticOnEvent(UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserData)
{
	CDXUTDialog* pDialog = (CDXUTDialog*)pUserData;
	CHECK_RETURN(pDialog);

	pDialog->OnEvent(nEvent, nControlID, pControl);
}